package com.xzc.algorithm.data_structure_ke.ArrayList.queue;

public class LoopQueue<T> implements Queue<T> {

    private T[] data;
    private int front;
    private int tail;
    private int size;

    public LoopQueue(int capacity) {
        data = (T[]) new Object[capacity + 1];
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public void enqueue(T t) throws Exception {
        if (isFull()) {
            throw new Exception("队列已满");
        }
        data[tail % data.length] = t;
        tail++;
        size++;
    }

    @Override
    public T dequeue() throws Exception {
        if (isEmpty()) {
            throw new Exception("队列是空的");
        }
        T t = data[front % data.length];
        front++;
        size--;
        return t;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (T i : data) {
            sb.append(i).append(",");
        }
        sb.append("]");
        sb.append(" size=").append(size).append(" length=").append(data.length).
                append(" front=").append(front % data.length).append(" tail=").append(tail % data.length);
        return sb.toString();
    }

    private boolean isFull() {
        return (tail + 1) % data.length == front;
    }
}
